﻿using Redis实战.Interface;
using Redis实战.Models;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace Redis实战.Services
{
    public class UserService
    {
        private readonly IUserRepository _userRepository;
        private readonly ICacheService _cacheService;
        private readonly ILogger<UserService> _logger;

        public UserService(
            IUserRepository userRepository,
            ICacheService cacheService,
            ILogger<UserService> logger)
        {
            _userRepository = userRepository;
            _cacheService = cacheService;
            _logger = logger;
        }

        // 统一缓存键生成逻辑
        private string GetUserCacheKey(int userId) => $"User:{userId}";

        /// <summary>
        /// 创建用户（仅保留带CancellationToken的版本，避免重载冲突）
        /// </summary>
        public async Task CreateUserAsync(User user, CancellationToken cancellationToken = default)
        {
            // 1. 调用仓储层保存到数据库（传递cancellationToken，匹配仓储接口）
            await _userRepository.CreateAsync(user, cancellationToken);

            // 2. 缓存新用户（此时user.Id已由数据库生成）
            var cacheKey = GetUserCacheKey(user.Id);
            await _cacheService.SetAsync(cacheKey, user, cancellationToken: cancellationToken);

            _logger.LogInformation("User {Id} created and cached", user.Id);
        }

        /// <summary>
        /// 删除用户（补充cancellationToken参数）
        /// </summary>
        public async Task DeleteUserAsync(int id, CancellationToken cancellationToken = default)
        {
            // 1. 先删除数据库记录（传递cancellationToken）
            await _userRepository.DeleteAsync(id, cancellationToken);

            // 2. 再删除缓存
            var cacheKey = GetUserCacheKey(id);
            await _cacheService.RemoveAsync(cacheKey, cancellationToken);

            _logger.LogInformation("删除用户并清除缓存: {UserId}", id);
        }

        /// <summary>
        /// 根据ID查询用户
        /// </summary>
        public async Task<User?> GetUserByIdAsync(int id, CancellationToken cancellationToken = default)
        {
            var cacheKey = GetUserCacheKey(id);
            var user = await _cacheService.GetAsync<User>(cacheKey, cancellationToken);

            if (user != null)
            {
                _logger.LogInformation("User {Id} retrieved from cache", id);
                return user;
            }

            // 缓存未命中，查询数据库
            user = await _userRepository.GetByIdAsync(id, cancellationToken);

            if (user != null)
            {
                await _cacheService.SetAsync(cacheKey, user, cancellationToken: cancellationToken);
                _logger.LogInformation("User {Id} cached successfully", id);
            }

            return user;
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        public async Task UpdateUserAsync(User user, CancellationToken cancellationToken = default)
        {
            await _userRepository.UpdateAsync(user, cancellationToken);

            // 更新缓存
            var cacheKey = GetUserCacheKey(user.Id);
            await _cacheService.SetAsync(cacheKey, user, cancellationToken: cancellationToken);

            _logger.LogInformation("User {Id} updated and cache refreshed", user.Id);
        }

        /// <summary>
        /// 清除用户缓存（统一参数风格）
        /// </summary>
        public async Task RemoveUserCacheAsync(int id, CancellationToken cancellationToken = default)
        {
            var cacheKey = GetUserCacheKey(id);
            await _cacheService.RemoveAsync(cacheKey, cancellationToken);
            _logger.LogInformation("已清除用户缓存: {UserId}", id);
        }
    }
}
